#include "act_update.hpp"
#include "rsp_range.hpp"
#include "../action_constants.hpp"
#include "../transaction.hpp"

using etcdserverpb::Compare;

namespace etcdv3 {

AsyncUpdateAction::AsyncUpdateAction(const ActionParameters& param)
    : Action(param) {
    Transaction transaction(parameters.key);
    transaction.init_compare(Compare::CompareResult::Compare_CompareResult_GREATER,
                             Compare::CompareTarget::Compare_CompareTarget_VERSION);

    transaction.setup_compare_and_swap_sequence(parameters.value, parameters.lease_id);

    context.set_deadline(parameters.gainDeadline());
    reader.reset(parameters.kv_stub->AsyncTxn(&context, transaction.txn_request, &cq_).release());

    reader->Finish(&reply, &status, (void*)this);
}

AsyncTxnResponse AsyncUpdateAction::ParseResponse() {
    AsyncTxnResponse txn_resp;
    if (!status.ok()) {
        txn_resp.set_error_code(status.error_code());
        txn_resp.set_error_message(status.error_message());
    } else {
        if (reply.succeeded()) {
            txn_resp.ParseResponse(parameters.key, parameters.withPrefix, reply);
            txn_resp.set_action(UPDATE_ACTION);
        } else {
            txn_resp.set_error_code(100);
            txn_resp.set_error_message("Key not found");
        }
    }
    return txn_resp;
}

}